<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { searchForWorkspaceRoot } from 'vite'
import {
  modifyRolePermission,
  modifyRoleRouter,
  roleAdd,
  roleFind,
  roleFindById,
  roleModify,
  roleRemove
} from '@/api/system/role'
import { Message, Modal } from '@arco-design/web-vue'
import { permissionFind } from '@/api/system/permission'
import { routerFind } from '@/api/system/router'

// 搜索表单
const searchForm = reactive({
  // 显示控制
  visible: false,
  // 搜索
  search: () => {
    roleFind({ pageNum: searchForm.list.pageNum, pageSize: searchForm.list.pageSize }).then(resp => {
      searchForm.list = resp.data
    })
  },
  // table 数据
  list: {
    total: 0,
    list: [],
    pageSize: 10,
    pageNum: 1
  }
})


// 操作数据表单
const operationFormRef = ref()
const operationForm = reactive({
  // 弹框标题
  title: '添加用户',
  // 是否显示
  visible: false,
  // 表单
  form: {
    code: '',
    id: null,
    name: '',
    permissions: [],
    routers: []
  },
  // 验证
  rules: [
    {}
  ],
  // 打开弹框
  open: () => {
    operationForm.title = '添加角色'
    operationForm.visible = true
    operationForm.reset()
  },
  // 修改权限
  modify: (record: any) => {
    operationForm.title = '修改角色'
    roleFindById(record.id).then(resp => {
      operationForm.form = resp.data
      operationForm.visible = true
    })
  },
  // 删除角色
  remove: (record: any) => {

    Modal.confirm({
      title: '警告！',
      content: `是否要删除 [${record.name}] ？`,
      onOk: () => {
        roleRemove(record.id).then(() => {
          searchForm.search()
        })
      }
    })

  },
  // 提交表单
  submit: ({ errors, values }: any) => {
    if (errors) {
      return
    }

    //如果id有值则为修改
    if (values.id) {
      roleModify(values).then(() => {
        operationForm.visible = false
        searchForm.search()
      })
      return
    }

    //新增
    roleAdd(values).then(() => {
      operationForm.visible = false
      searchForm.search()
    })
  },
  reset: () => {
    operationForm.form = {
      code: '',
      id: null,
      name: '',
      permissions: [],
      routers: []
    }
  }
})

//分配路由权限
const allocation = reactive({
  visible: false,
  form: {
    id: null,
    // 权限列表
    permissions: [],
    // 路由列表
    routers: []
  },
  //打开分配路由权限
  open: (record: any) => {
    roleFindById(record.id).then(resp => {
      allocation.form = resp.data
      // 设置选择的key
      allocation.routerCheckList = resp.data.routers.map((val: any) => val.id)
      allocation.permissionCheckList = resp.data.permissions.map((val: any) => val.id)
      allocation.visible = true
    })
  },
  //权限列表（总）
  permissionList: [],
  permissionExpandedKeys: [],
  permissionCheckList: [],
  //路由列表（总）
  routerList: [],
  routerTreeList: [],
  routerExpandedKeys: [],
  routerCheckList: [],
  loadPermissionRouter: () => {
    permissionFind({ pageSize: 9999999999, pageNum: 1 }).then(resp => {
      allocation.permissionList = resp.data.list
      allocation.permissionExpandedKeys = resp.data.list.map((val: any) => val.id)
    })
    routerFind({ pageSize: 999999999, pageNum: 1 }).then(resp => {
      const data = resp.data.list
      allocation.routerList = data

      // 未知问题，所以重新过滤一下数据
      allocation.routerTreeList = data.map((val: any) => ({
        id: val.id,
        name: val.name,
        children: val.children
      }))

      allocation.routerExpandedKeys = data.map((val: any) => val.id)
    })
  },
  // 提交权限
  submitPermission: () => {
    modifyRolePermission({
      roleId: allocation.form.id,
      permissions: allocation.permissionCheckList
    })
  },
  // 提交路由
  submitRouter: () => {
    modifyRoleRouter({
      roleId: allocation.form.id,
      routers: allocation.routerCheckList
    })
  }
})


onMounted(() => {
  // 获取角色列表
  searchForm.search()
  //获取权限路由列表
  allocation.loadPermissionRouter()
  document.title = 'Rocc管理系统 角色管理'
})

</script>

<template>
  <div class="w-full h-full">
    <div class="flex justify-between mr-1">
      <a-space wrap>
        <a-button type="primary" @click="operationForm.open">
          <template #icon>
            <icon-plus />
          </template>
          添加角色
        </a-button>
      </a-space>
      <a-space>
        <a-tooltip content="刷新列表" position="tr">
          <a-button size="small" shape="circle">
            <template #icon>
              <icon-refresh />
            </template>
          </a-button>
        </a-tooltip>
      </a-space>
    </div>
    <!--  新增修改弹框  -->
    <a-drawer v-model:visible="operationForm.visible" :title="operationForm.title" :width="500" :footer="false">
      <a-form ref="operationFormRef" :model="operationForm.form" @submit="operationForm.submit">
        <a-form-item label="角色代码" field="code" :disabled="operationForm.form.id">
          <a-input v-model="operationForm.form.code" />
        </a-form-item>
        <a-form-item label="角色名称" field="name">
          <a-input v-model="operationForm.form.name" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">
            提交
          </a-button>
        </a-form-item>
      </a-form>
    </a-drawer>
    <!-- 分配路由权限弹框  -->
    <a-drawer v-model:visible="allocation.visible" :header="false" :width="500" :footer="false">
      <a-tabs>
        <a-tab-pane title="权限分配" key="permission">
          <a-tree
            :checkable="true"
            :field-names="{
                        key: 'id',
                        title: 'name',
                        children: 'children',
                      }"
            :data="allocation.permissionList"
            v-model:checked-keys="allocation.permissionCheckList"
            v-model:expanded-keys="allocation.permissionExpandedKeys"
          />
          <a-space class="mt-5">
            <a-button type="primary" @click="allocation.submitPermission">提交权限分配</a-button>
            <a-button @click="allocation.visible =false">关闭</a-button>
          </a-space>
        </a-tab-pane>
        <a-tab-pane title="路由分配" key="router">
          <a-tree
            :checkable="true"
            :field-names="{
                        key: 'id',
                        title: 'name',
                        children: 'children',
                      }"
            :data="allocation.routerTreeList"
            v-model:checked-keys="allocation.routerCheckList"
            v-model:expanded-keys="allocation.routerExpandedKeys"
          />
          <a-space class="mt-5">
            <a-button type="primary" @click="allocation.submitRouter">提交路由分配</a-button>
            <a-button @click="allocation.visible =false">关闭</a-button>
          </a-space>
        </a-tab-pane>
      </a-tabs>
    </a-drawer>
    <!-- 列表弹框   -->
    <a-table :data="searchForm.list.list" :pagination="false">
      <template #columns>
        <a-table-column title="ID" data-index="id"></a-table-column>
        <a-table-column title="角色名称" data-index="name"></a-table-column>
        <a-table-column title="角色代码" data-index="code"></a-table-column>
        <a-table-column title="操作" width="160">
          <template #cell="{record}">
            <a-space>
              <a-button status="warning" @click="operationForm.modify(record)">
                <template #icon>
                  <icon-edit />
                </template>
                修改
              </a-button>
              <a-button status="success" @click="allocation.open(record)">
                <template #icon>
                  <icon-unlock />
                </template>
                配置权限路由
              </a-button>
              <a-button status="danger" @click="operationForm.remove(record)">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <div class="mt-4 flex justify-end">
      <a-pagination v-model:current="searchForm.list.pageNum"
                    v-model:page-size="searchForm.list.pageSize"
                    :total="searchForm.list.total"
                    @change="searchForm.search"
                    show-total
                    show-jumper
                    show-page-size
      ></a-pagination>
    </div>
  </div>
</template>

<style scoped>

</style>
